package com.run.go.gearbox.mysql.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.List;

public class NettyMysqlDecoder extends ByteToMessageDecoder {
    private final static Logger log = LoggerFactory.getLogger(Decoder.class);

    private Decoder decoder;

    public NettyMysqlDecoder(Decoder decoder) {
        this.decoder = decoder;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {
        // debug buffer since 2017-10-15 little-pan
        final boolean debug = log.isDebugEnabled();
        log.info("Decoded buffer#{}: {}", buffer.hashCode(), buffer);

        final InputStream in = new ByteBufInputStream(buffer);
        try {
            Object obj = decoder.decode(in, ctx.channel());
            if (log.isDebugEnabled() && null != obj) {
                log.debug("Decoded message: {}", obj);
            }
            if (obj != null) {
                out.add(obj);
            }
        } finally {
            in.close();
        }
    }
}